
"""
__version__ = "$Revision: 1.13 $"
__date__ = "$Date: 2005/12/13 11:13:23 $"
"""

import rfc822, datetime

ORIGINAL_MESSAGE_HEADER = '-----Original Message-----'

# this should be locale specific
# and moved to a common module?
def dateString(tztuple):
    #print tztuple
    if isinstance(tztuple, str):
        # need to convert rfc822 header to date
        # format used in list?
        return tztuple
    else:
        return datetime.datetime(tztuple[0], tztuple[1], tztuple[2], tztuple[3], tztuple[4]).strftime('%m/%d/%y %H:%M')

def joinList(listX):
    text = ", ".join(listX)
    return text.replace('\n', '')

def filteredSubject(subject):
    # chop out spam identifier by getting rid of spaces
    # and id after main subject
    listX = subject.split('    ')
    return listX[0]

# the blacklist is stored in a blacklist.txt
# file with one address per line making it
# easy to edit outside of the app as well as convert
# into a list at runtime
def loadList(filename):
    try:
        f = open(filename, 'r')
        temp = f.read()
        listX = temp.splitlines()
        f.close()
        dictX = {}
        for i in listX:
            dictX[i] = None
    except IOError:
        dictX = {}
    return dictX
    
def saveList(filename, dictX):
    listX = dictX.keys()
    listX.sort()
    try:
        f = open(filename, 'w')
        temp = "\n".join(listX)
        f.write(temp)
        f.close()
    except IOError:
        print "argh, couldn't write the file, what do we do?"

# adapted from Moshe Zadka <pms@zadka.site.co.il>
# pms Actions.py
# should X-UIDL be used here as well
# the messages I'm sending don't appear to have any other id
def getReferences(msg):
    old = msg.get('references')
    new = msg['message-id']
    if old:
        # old could just have ids separated by spaces
        # like this <> <> <>
        # see wx-dev and wx-users messages in which case
        # i'm not sure if we should be using a comma or adding commas
        return new + ', ' + old
    else:
        return new

def getInReplyTo(msg):
    return msg['message-id']

def getBody(msg):
    if msg.get_main_type() is None:
        # subscription notices from mailman don't appear
        # to have a main content type
        text = msg.get_payload(decode=1)
    else:
        # try MIME
        counter = 0
        text = None
        for part in msg.walk():
            # multipart/* are just containers
            partType = part.get_type()
            print counter, partType
            if part.get_main_type() == 'multipart':
                continue
            if partType in ['text/plain', 'text/html']:
                if text is None:
                    # only display the first payload
                    # but there might be attachments...
                    text = part.get_payload(decode=1)
            counter += 1
        # I'm not sure when this case would occur
        # so it might be pointless
        if text is None and msg.get_main_type in ['text/plain', 'text/html']:
            text = msg.get_payload(decode=1)
    return text

def getAttachments(msg):
    attachments = []
    # try MIME
    counter = 0
    for part in msg.walk():
        # multipart/* are just containers
        partType = part.get_type()
        if part.get_main_type() == 'multipart':
            continue
        filename = part.get_filename()
        if filename is not None:
            if not filename:
                ext = mimetypes.guess_extension(part.get_type())
                if not ext:
                    # Use a generic bag-of-bits extension
                    ext = '.bin'
                filename = 'part-%03d%s' % (counter, ext)
            print counter, partType, filename
            attachments.append({'part':counter, 'type':partType, 'filename':filename})
        counter += 1
    return attachments

def filteredUser(fromAddress, addresses):
    ret = []
    addresses = rfc822.AddrlistClass(addresses).getaddrlist()
    for address in addresses:
        if address[1] == fromAddress:
            continue
        else:
            ret.append(rfc822.dump_address_pair(address))
    return "; ".join(ret)

